package com.shanzhu.parking.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token 配置
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    
    /**
     * 注册 Sa-Token 全局过滤器 
     */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
            // 拦截与放行规则
            .addInclude("/**")
            .addExclude("/favicon.ico")
            // 前置函数：在每次拦截到请求后触发 
            .setBeforeAuth(obj -> {
                // 获取请求的Origin
                String origin = SaHolder.getRequest().getHeader("Origin");
                if (origin == null) {
                    origin = "http://localhost:9272";
                }
                
                // 允许指定域名的跨域请求
                SaHolder.getResponse()
                    .setHeader("Access-Control-Allow-Origin", origin)
                    .setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
                    .setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, satoken, X-Requested-With")
                    .setHeader("Access-Control-Max-Age", "3600")
                    .setHeader("Access-Control-Allow-Credentials", "true");
                
                // 如果是预检请求，则立即返回到前端
                if("OPTIONS".equals(SaHolder.getRequest().getMethod())) {
                    SaRouter.back();
                }
            })
            // 不进行登录校验
            .setAuth(obj -> {
                // 不做任何校验
            });
    }
} 